package com.iyao_app.mvp.completeinfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.UpdateUser;
import com.iyao_app.entry.UploadImage;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.mvp.home.MainActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.CustomDialog;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.PickImageLoader;
import com.iyao_app.util.ResourcesUtils;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.KeyboardUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.TimeUtils;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.rockerhieu.emojicon.EmojiconEditText;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/14.
 */

public class CompleteInfoActivity extends BaseActivityWithHead {
    @BindView(R.id.rl_root)
    RelativeLayout mRlRoot;
    @BindView(R.id.sdv_photo)
    SimpleDraweeView mSdvPhoto;
    @BindView(R.id.et_nickname)
    EmojiconEditText mEtNickname;
    @BindView(R.id.tv_man)
    TextView mTvMan;
    @BindView(R.id.tv_woman)
    TextView mTvWoman;
    @BindView(R.id.tv_year)
    TextView mTvYear;
    @BindView(R.id.tv_month)
    TextView mTvMonth;
    @BindView(R.id.tv_day)
    TextView mTvDay;
    @BindView(R.id.et_invitation)
    EditText mEtInvitation;
    @BindView(R.id.tv_fail)
    TextView mTvFail;
    private int sex = 0;
    final int SEX_MAN = 1;
    final int SEX_WOMAN = 2;
    final int IMAGE_PICKER = 1;

    private TimePickerView pvTime;
    private Bitmap bm;
    private String id;
    private long birthDay = 0;
    private String headImage = null;
    private int type;
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_complete_info);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra(Contants.TYPE, 0);
        if (type == 1) {
            id = getIntent().getStringExtra("id");
        } else {
            user = (User) getIntent().getSerializableExtra(Contants.OTHER_FIELD);
            id = user.id;
        }
        setTitleTV(ResourcesUtils.getString(R.string.complete_info));
        initPicker();
        bm = BitmapFactory.decodeResource(this.getResources(), R.mipmap.bg_ditu_denglu);
        BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);
        mRlRoot.setBackgroundDrawable(bd);
        mEtNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEtNickname.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    KeyboardUtils.hideSoftInput(mEtNickname);
                }

                return false;
            }
        });
    }

    @OnClick({R.id.sdv_photo, R.id.tv_man, R.id.tv_woman, R.id.lin_birthday, R.id.tv_confirm, R.id.rl_root})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sdv_photo:
                KeyboardUtils.hideSoftInput(this);
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.tv_man:
                KeyboardUtils.hideSoftInput(this);
                sex = SEX_MAN;
                setSex(sex);
                break;
            case R.id.tv_woman:
                KeyboardUtils.hideSoftInput(this);
                sex = SEX_WOMAN;
                setSex(sex);
                break;
            case R.id.lin_birthday:
                KeyboardUtils.hideSoftInput(this);
                timePick();
                break;
            case R.id.tv_confirm:
                KeyboardUtils.hideSoftInput(this);
                check();
                break;
            case R.id.rl_root:
                KeyboardUtils.hideSoftInput(this);
                break;

        }
    }

    private void check() {
        String s = null;
        if (TextUtils.isEmpty(headImage)) {
            s = getString(R.string.please_up_head);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(s);
            return;
        }
        if (TextUtils.isEmpty(mEtNickname.getText().toString().trim())) {
            s = getString(R.string.please_up_name);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(s);
            return;
        }
        if (sex == 0) {
            s = getString(R.string.please_up_sex);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(s);
            return;
        }
        if (TextUtils.isEmpty(mTvYear.getText().toString().trim())) {
            s = getString(R.string.please_up_birthday);
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            mTvFail.setVisibility(View.VISIBLE);
            mTvFail.startAnimation(shake);
            mTvFail.setText(s);
            return;
        }
        upLoadImage();
    }


    private void upLoadImage() {
        showDialog();
        Flowable.just(headImage)
                .observeOn(Schedulers.io())
                .map(new Function<String, File>() {
                    @Override
                    public File apply(String s) throws Exception {
                        return Luban.with(CompleteInfoActivity.this).load(s).get().get(0);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        int[] imageInfo = ImageUtils.getImageWidthHeight(file);
                        LogUtil.e(imageInfo[0] + "=====" + imageInfo[1]);
                        final HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("file", file);
                        NetUtils.getInstance().uploadImage(RequestUrl.UPLOAD_FILE, imageInfo[0], imageInfo[1], hashMap, new NetCallBack() {
                            @Override
                            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                                if (code == Contants.SUCCESS_CODE) {

                                    UploadImage uploadImage = model.getModel();
                                    if (uploadImage != null && !TextUtils.isEmpty(uploadImage.getFileUrl())) {
                                        complete(uploadImage.getFileUrl());
                                    }
                                } else {
                                    closeDialog();
                                    if (!TextUtils.isEmpty(message)) {
                                        Animation shake = AnimationUtils.loadAnimation(CompleteInfoActivity.this, R.anim.shake);
                                        mTvFail.setVisibility(View.VISIBLE);
                                        mTvFail.startAnimation(shake);
                                        mTvFail.setText(message);
                                    }
                                }
                            }

                            @Override
                            public void onFail(String message, int code) {
                                Toast.makeText(CompleteInfoActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                                closeDialog();
                            }
                        }, UploadImage.class);
                    }
                });

    }

    private void complete(String image) {

        NetUtils.getInstance().completeInfo(id, String.valueOf(birthDay), image, mEtNickname.getText().toString().trim(), String.valueOf(sex), new NetCallBack() {
            @Override
            public void onSuccess(final String message, final int code, String response, ResultModel model) {
                closeDialog();
                if (code == 20000) {
                    if (type == 0) {
                        user.userId = id;
                        user.nickname = mEtNickname.getText().toString().trim();
                        user.birthday = birthDay;
                        user.sex = sex;
                        DbUtil.updateUserInfo(user);
                        upDateUser();

                    } else {
                        finish();
                    }

                } else {
                    if (!TextUtils.isEmpty(message)) {
                        Animation shake = AnimationUtils.loadAnimation(CompleteInfoActivity.this, R.anim.shake);
                        mTvFail.setVisibility(View.VISIBLE);
                        mTvFail.startAnimation(shake);
                        mTvFail.setText(message);
                    }

                }
            }

            @Override
            public void onFail(String message, int code) {
                closeDialog();
            }
        }, null);
    }

    private void upDateUser() {
        if (DbUtil.getUser() != null && !TextUtils.isEmpty(DbUtil.getUser().id)) {
            NetUtils.getInstance().userInfo(DbUtil.getUser().id, new NetCallBack() {
                @Override
                public void onSuccess(String message, int code, String response, ResultModel model) {
                    if (code == Contants.SUCCESS_CODE) {
                        if (model != null) {
                            UpdateUser updateUser = model.getModel();
                            User user = DbUtil.getUser();
                            user.id = updateUser.id;
                            user.token = updateUser.token;
                            user.nickname = updateUser.nickname;
                            user.sex = updateUser.sex;
                            user.avatarUrl = updateUser.avatarUrl;
                            DbUtil.updateUserInfo(user);

                            Intent intent = new Intent(CompleteInfoActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
                        }
                    }
                }

                @Override
                public void onFail(String message, int code) {

                }
            }, UpdateUser.class);
        }
    }

    private void setSex(int sex) {
        if (mTvFail.getVisibility() == View.VISIBLE) {
            mTvFail.setVisibility(View.GONE);
        }
        LogUtil.e("====" + sex);
        switch (sex) {
            case SEX_MAN:
                mTvMan.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                mTvWoman.setTextColor(ResourcesUtils.getColor(R.color.text_color_rgb_153_code_999));
                mTvMan.getPaint().setFakeBoldText(true);
                mTvWoman.getPaint().setFakeBoldText(false);
                mTvMan.setTextSize(16);
                mTvWoman.setTextSize(14);
                break;
            case SEX_WOMAN:
                mTvMan.setTextColor(ResourcesUtils.getColor(R.color.text_color_rgb_153_code_999));
                mTvWoman.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                mTvMan.getPaint().setFakeBoldText(false);
                mTvWoman.getPaint().setFakeBoldText(true);
                mTvWoman.setTextSize(16);
                mTvMan.setTextSize(14);
                break;
        }
        new CustomDialog(this)
                .setConfirmText(ResourcesUtils.getString(R.string.confirm))
                .setContent(ResourcesUtils.getString(R.string.select_sex_message))
                .setCanceled(false)
                .setOnConfirmClickListener(null)
                .show();
    }

    private void timePick() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        selectedDate.set(1990, 1, 1);
        //正确设置方式 原因：注意事项有说明
        startDate.set(1900, 1, 1);

        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (date != null) {
                    if (mTvFail.getVisibility() == View.VISIBLE) {
                        mTvFail.setVisibility(View.GONE);
                    }
                    String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                    String[] split = time.split("-");
                    mTvYear.setText(split[0]);
                    mTvMonth.setText(split[1]);
                    mTvDay.setText(split[2]);
                    birthDay = date.getTime();
                }
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setTextColorCenter(Color.WHITE)
                .setTextColorOut(Color.GRAY)
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(ResourcesUtils.getColor(R.color.app_black_bg))//标题背景颜色 Night mode
                .setBgColor(ResourcesUtils.getColor(R.color.app_black_bg))
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(1000);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(1000);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                if (mTvFail.getVisibility() == View.VISIBLE) {
                    mTvFail.setVisibility(View.GONE);
                }
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);
                mSdvPhoto.setImageURI(ImageUtils.IMAGE_FILE + imageItem.path);
                headImage = imageItem.path;
                LogUtil.e("===" + imageItem.path);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapDrawable bd = (BitmapDrawable) mRlRoot.getBackground();
        bm = null;
        mRlRoot.setBackgroundDrawable(null);
        bd.setCallback(null);
        bd.getBitmap().recycle();
    }
}
